package com.leyou.cart.intercepotrs;

import com.leyou.cart.utils.UserHolder;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * 拦截用户请求，获取当前用户的信息
 * @author 虎哥
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            // 获取cookie中的token
            String token = CookieUtils.getCookieValue(request, "LY_TOKEN");
            // 解析token，取出用户
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
            UserInfo user = payload.getUserInfo();
            // 保存用户信息
            UserHolder.setUser(user);
            return true;
        } catch (UnsupportedEncodingException e) {
            log.error("解析用户身份失败，原因：{}", e.getMessage());
            throw new LyException(500, e.getMessage(), e);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.removeUser();
    }
}
